package com.znb.okdown.net;


import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

public class SSEClient {

    private static final String TAG = "SSEClient";

    private static SSEClient mInstance;

    private OkHttpClient okHttpClient;

    private SSEClient() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }

    public static synchronized SSEClient getInstance() {
        if (mInstance == null) {
            mInstance = new SSEClient();
        }
        return mInstance;
    }

    private EventSourceListener eventSourceListener;

    //3
    public void chatOkhttpSSE(String content) {
        String url = "http://umafrp.chinaxdr.com/chatglm/v1/chat/completions";
        String completionJSON = "{\"model\":\"chatglm3-6b\",\"messages\":[{\"role\":\"user\",\"content\":" + content + "}],\"temperature\":0.8,\"top_p\":0.8,\"max_tokens\":0,\"stream\":true,\"repetition_penalty\":1.1}";
        MediaType mediaType = MediaType.get("application/json");
        RequestBody body = RequestBody.create(mediaType, completionJSON);
        Request request = new Request.Builder().url(url).method("POST", body).build();
        EventSource.Factory factory = EventSources.createFactory(okHttpClient);

        eventSourceListener = new EventSourceListener() {
            /**
             * {@inheritDoc}
             */
            @Override
            public void onOpen(final EventSource eventSource, final Response response) {
                Log.e(TAG, "建立sse连接...");

            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void onEvent(final EventSource eventSource, final String id, final String type, final String data) {
                Log.e(TAG, "建立sse连接成功: " + data);
                if (mSseConnectSucccesListener != null) {
                    mSseConnectSucccesListener.getData(data);
                }
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void onClosed(final EventSource eventSource) {
                Log.e(TAG, "建立sse连接关闭");
                //连接失败尝试重新连接
                if (request != null && eventSourceListener != null) {
                    Log.e(TAG, "连接异常，正在尝试重新连接...");
                    factory.newEventSource(request, eventSourceListener);
                } else {
                    Log.e(TAG, "连接异常，请稍后重试");
                }
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void onFailure(final EventSource eventSource, final Throwable t, final Response response) {
                Log.e(TAG,"连接服务端时出现异常-----" + t.getMessage());
                //连接失败尝试重新连接
                /*if (request != null && eventSourceListener != null) {
                    Log.e(TAG, "连接异常，正在尝试重新连接...");
                    factory.newEventSource(request, eventSourceListener);
                } else {
                    Log.e(TAG, "连接异常，请稍后重试");
                }*/
            }
        };
        //创建事件
        factory.newEventSource(request, eventSourceListener);
        //由于springboot test异步的，加下面代码卡住同步
//        CountDownLatch countDownLatch = new CountDownLatch(1);
//        try {
//            countDownLatch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

    }


    //建立监听回调
    private SSEConnectSucccesListener mSseConnectSucccesListener;

    public void getSSEMessage(SSEConnectSucccesListener sseConnectSucccesListener) {
        mSseConnectSucccesListener = sseConnectSucccesListener;
    }

    public interface SSEConnectSucccesListener {
        void getData(String data);
    }
}